<?php


namespace app\api\service;


use app\api\model\Order as OrderModel;
use app\lib\enum\OrderStatusEnum;
use app\lib\exception\OrderException;
use app\lib\exception\TokenException;
use think\Exception;
use think\facade\Log;
use EasyWeChat\Factory;

//require_once "../../../extend/WxPay/WxPay.Api.php";

class Pay
{
    private $orderID;
    private $orderNO;

    public function __construct($orderID)
    {
        $this->orderID = $orderID;
        if (!$this->orderID) {
            throw new Exception('订单号不允许为NULL');
        }
    }

    public function pay()
    {
        $this->checkOrderValid();
        $orderService = new Order();
        $status = $orderService->checkOrderStock($this->orderID);
        if (!$status['pass']) {
            return $status;
        }
        return $this->makeWxPreOrder($status['orderPrice']);
    }

    private function makeWxPreOrder($totalPrice)
    {
        $openid = Token::getCurrentTokenVar('openid');
        if (!$openid) {
            throw new TokenException();
        }
        //原生微信支付
//        $wxOrderData = new \WxPayUnifiedOrder();
//        $wxOrderData->SetOut_trade_no($this->orderNO);
//        $wxOrderData->SetTrade_type('JSAPI');
//        $wxOrderData->SetTotal_fee($totalPrice*100);
//        $wxOrderData->SetBody('手办潮玩');
//        $wxOrderData->SetOpenid($openid);
//        //todo
//        $wxOrderData->SetNotify_url('');
//        return $this->getPaySignature($wxOrderData);

        $config = [
            'app_id' => config('wx.app_id'),
            'mch_id' => config('wx.mch_id'),
            'secret' => config('wx.app_secret'),
            'key'=> 'signatesussdfsdfsfasdadaddfsdfre',
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];

        $app = Factory::payment($config);

        $result = $app->order->unify([
            'body' => '手办潮玩',
            'out_trade_no' => $this->orderNO,
            'total_fee' => $totalPrice * 100,
            //'spbill_create_ip' => '', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => config('wx.pay_back_url'),
            'trade_type' => 'JSAPI',
            'openid' => $openid,
        ]);

        if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') {
            Log::record($result, 'error');
            Log::record('获取预支付订单失败', 'error');
        }

        $this->recordPreOrder($result);
        $sign = $this->sign($app,$result);
        return $sign;
    }

    private function recordPreOrder($wxOrder)
    {
        OrderModel::where('id','=',$this->orderID)->update(['prepay_id'=>$wxOrder['prepay_id']]);
    }

    private function sign($app,$wxOrder)
    {
        // 返回数组;
        return $app->jssdk->bridgeConfig($wxOrder['prepay_id'], false);
    }

    private function getPaySignature($wxOrderData)
    {
//        $wxOrder = \WxPayApi::unifiedOrder($wxOrderData);
//        if ($wxOrder['return_code'] != 'SUCCESS' || $wxOrder['result_code'] != 'SUCCESS') {
//            Log::record($wxOrder, 'error');
//            Log::record('获取预支付订单失败', 'error');
//        }
//        return null;
    }

    private function checkOrderValid()
    {
        $order = OrderModel::where('id',$this->orderID)->findOrEmpty();
        if ($order->isEmpty()) {
            throw new OrderException();
        }
        if (!Token::isValidOperate($order->user_id)) {
            throw new TokenException([
                'msg' => '订单与用户不匹配',
                'errorCode' => 10003
            ]);
        }
        if ($order->status != OrderStatusEnum::UNPAID) {
            throw new OrderException([
                'msg' => '订单已支付过啦',
                'errorCode' => 80003,
                'code' => 400
            ]);
        }
        $this->orderNO = $order->order_no;
        return true;
    }
}